package com.anti.modular.bus.buscostincomeexpenses.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.anti.core.context.login.LoginContextHolder;
import com.anti.jdbc.DBUtils;
import com.anti.jdbc.support.page.PageParam;
import com.anti.jdbc.support.page.PageResult;
import com.anti.commom.core.exception.BusinessException;
import com.anti.modular.bus.buscostbillhydropower.param.BusCostBillHydropowerParam;
import com.anti.modular.bus.buscostincomeexpenses.entity.BusCostIncomeExpenses;
import com.anti.modular.bus.buscostincomeexpenses.entity.BusCostIncomeInsertExpenses;
import com.anti.modular.bus.buscostincomeexpenses.enums.BusCostIncomeExpensesExceptionEnum;
import com.anti.modular.bus.buscostincomeexpenses.node.BusCostIncomeExpensesNode;
import com.anti.modular.bus.buscostincomeexpenses.param.BusCostIncomeExpensesParam;
import com.anti.modular.bus.buscostincomeexpenses.service.BusCostIncomeExpensesService;
import com.anti.modular.sys.auth.factory.TreeBuildFactory;
import com.anti.modular.sys.menu.entity.SysMenu;
import com.anti.modular.sys.menu.node.MenuBaseTreeNode;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 收入支出配置service接口实现类
 *
 * @author anti
 * @date 2021-04-08 14:15:30
 */
@Service
public class BusCostIncomeExpensesServiceImpl implements BusCostIncomeExpensesService {
    @Resource
    DBUtils dbUtils;

    @Override
    public BusCostIncomeExpenses getById(BusCostIncomeExpensesParam busCostIncomeExpensesParam){
        String sql="select * from bus_cost_income_expenses where id =? ";
        return dbUtils.get(sql,BusCostIncomeExpenses.class,busCostIncomeExpensesParam.getId());
    }

    @Override
    public PageResult page(PageParam pageParam,BusCostIncomeExpensesParam busCostIncomeExpensesParam) {
        StringBuilder sb=new StringBuilder("select * from bus_cost_income_expenses where status=0 ");
        ArrayList<Object> param = CollectionUtil.newArrayList();
        if (ObjectUtil.isNotNull(busCostIncomeExpensesParam)) {
            if (ObjectUtil.isNotEmpty(busCostIncomeExpensesParam.getType())) {
                sb.append(" and type = ?");
                param.add(busCostIncomeExpensesParam.getType());
            }
            // 根据名称 查询
            if (ObjectUtil.isNotEmpty(busCostIncomeExpensesParam.getName())) {
               sb.append(" and name = ?");
               param.add(busCostIncomeExpensesParam.getName());
            }
        }
        return dbUtils.query(pageParam,sb.toString(),param.toArray());
    }

    @Override
    public List<Map<String, Object>> tree(BusCostIncomeExpensesParam busCostIncomeExpensesParam) {
        String sql="select id as code ,name  from bus_cost_income_expenses where type =?  and status=0 and pid=0";
        List<Map<String, Object>> mapList = dbUtils.query(sql, busCostIncomeExpensesParam.getType());
        return mapList;
    }

    @Override
    public List<BusCostIncomeInsertExpenses> list(BusCostIncomeExpensesParam busCostIncomeExpensesParam) {
        StringBuilder sb=new StringBuilder("select * from bus_cost_income_expenses where status=0 ");
        ArrayList<Object> param = CollectionUtil.newArrayList();
        if (ObjectUtil.isNotNull(busCostIncomeExpensesParam)) {
            if (ObjectUtil.isNotEmpty(busCostIncomeExpensesParam.getType())) {
                sb.append(" and type = ?");
                param.add(busCostIncomeExpensesParam.getType());
            }
            // 根据名称 查询
            if (ObjectUtil.isNotEmpty(busCostIncomeExpensesParam.getName())) {
                sb.append(" and name = ?");
                param.add(busCostIncomeExpensesParam.getName());
            }
        }
        //根据排序升序排列，序号越小越在前
        List<BusCostIncomeInsertExpenses> sysMenuList = dbUtils.query(sb.toString(),BusCostIncomeInsertExpenses.class,param.toArray());
        //将结果集处理成树
        return new TreeBuildFactory<BusCostIncomeInsertExpenses>().doTreeBuild(sysMenuList);

    }

    @Override
    public List<BusCostIncomeExpenses> getListByType(Integer type) {
        String sql="select * from bus_cost_income_expenses where status=0 and type = ?";
        return dbUtils.query(sql,BusCostIncomeExpenses.class,type);
    }

    @Override
    public void add(BusCostIncomeExpensesParam busCostIncomeExpensesParam) {
        checkParam(busCostIncomeExpensesParam,false);
        BusCostIncomeExpenses busCostIncomeExpenses = new BusCostIncomeExpenses();
        BeanUtil.copyProperties(busCostIncomeExpensesParam, busCostIncomeExpenses);
        busCostIncomeExpenses.setStatus(0);
        busCostIncomeExpenses.setCreateTime(new Date());
        busCostIncomeExpenses.setCreateUser(LoginContextHolder.me().getSysLoginUserId());
        dbUtils.insert(busCostIncomeExpenses);
    }


    public void delete(BusCostIncomeExpensesParam busCostIncomeExpensesParam) {
        BusCostIncomeExpenses busCostIncomeExpenses = this.queryBusCostIncomeExpenses(busCostIncomeExpensesParam);
        Long sysLoginUserId = LoginContextHolder.me().getSysLoginUserId();
        Date date = new Date();
        if (busCostIncomeExpensesParam.getLevel().equals("1")){
            String sql="select * from bus_cost_income_expenses where pid=? and status=0";
            List<BusCostIncomeExpenses> query = dbUtils.query(sql, BusCostIncomeExpenses.class, busCostIncomeExpensesParam.getId());
            query.forEach(busCostIncomeExpenses1 -> {
                busCostIncomeExpenses1.setStatus(2);
                busCostIncomeExpenses1.setUpdateTime(date);
                busCostIncomeExpenses1.setUpdateUser(sysLoginUserId);
                dbUtils.update(busCostIncomeExpenses1);
            });
        }
        busCostIncomeExpenses.setStatus(2);
        busCostIncomeExpenses.setUpdateTime(date);
        busCostIncomeExpenses.setUpdateUser(sysLoginUserId);
        dbUtils.update(busCostIncomeExpenses);
    }

    public void edit(BusCostIncomeExpensesParam busCostIncomeExpensesParam) {
        checkParam(busCostIncomeExpensesParam,true);
        BusCostIncomeExpenses busCostIncomeExpenses = this.queryBusCostIncomeExpenses(busCostIncomeExpensesParam);
        BeanUtil.copyProperties(busCostIncomeExpensesParam, busCostIncomeExpenses);
        busCostIncomeExpenses.setUpdateTime(new Date());
        busCostIncomeExpenses.setUpdateUser(LoginContextHolder.me().getSysLoginUserId());
        dbUtils.update(busCostIncomeExpenses);
    }

    @Override
    public BusCostIncomeExpenses detail(BusCostIncomeExpensesParam busCostIncomeExpensesParam) {
        return this.queryBusCostIncomeExpenses(busCostIncomeExpensesParam);
    }

    /**
     * 获取收入支出配置
     *
     * @author anti
     * @date 2021-04-08 14:15:30
     */
    private BusCostIncomeExpenses queryBusCostIncomeExpenses(BusCostIncomeExpensesParam busCostIncomeExpensesParam) {
        BusCostIncomeExpenses busCostIncomeExpenses = this.getById(busCostIncomeExpensesParam);
        if (ObjectUtil.isNull(busCostIncomeExpenses)) {
            throw new BusinessException(BusCostIncomeExpensesExceptionEnum.NOT_EXIST);
        }
        return busCostIncomeExpenses;
    }

    private void checkParam(BusCostIncomeExpensesParam busCostIncomeExpensesParam, boolean isExcludeSelf){
        Long id = busCostIncomeExpensesParam.getId();
        String depositName = busCostIncomeExpensesParam.getName();
        String level = busCostIncomeExpensesParam.getLevel();
        String type = busCostIncomeExpensesParam.getType();
        Long pid = busCostIncomeExpensesParam.getPid();
        //构建带name查询条件
        StringBuilder nameSb=new StringBuilder("select count(*) from bus_cost_income_expenses where status =0 and name =? and level=? and type=? ");
        ArrayList<Object> nameParams = CollectionUtil.newArrayList();
        nameParams.add(depositName);
        nameParams.add(level);
        nameParams.add(type);
        if (pid==0){
            nameSb.append(" and pid = 0");
        }else {
            nameSb.append(" and pid <> 0");
        }
        //如果排除自己，则增加查询条件主键id不等于本条id
        if (isExcludeSelf) {
            nameSb.append(" and id <> ?");
            nameParams.add(id);
        }
        //查询重复记录的数量
        int countByName = dbUtils.getIntValue(nameSb.toString(),nameParams.toArray());

        //如果存在重复的记录，抛出异常，直接返回前端
        if (countByName >= 1) {
            throw new BusinessException(0,"該支出類別已存在");
        }
    }

}
